package com.chunk.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chunk.util.Cons;

/**
 * 分片上传 ,针对大文件分片上传,并为对落地文件做任何处理。
 * 
 * @author 王远航
 *
 */
@WebServlet(name = "FileChunkUploadServlet", urlPatterns = "/chunkUpload")
public class FileChunkUploadServlet extends HttpServlet {
	
	private static final Logger commonLogger = LoggerFactory.getLogger(FileChunkUploadServlet.class);
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setHeaderEncoding("utf-8");

		String fileMd5 = null;
		String chunk = null;
		try {
			List<FileItem> items = sfu.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) { //普通数据
					String fieldName = item.getFieldName();
					if (fieldName.equals("fileMd5")) {
						fileMd5 = item.getString("utf-8");
					}
					if (fieldName.equals("chunk")) {
						chunk = item.getString("utf-8");
					}
				} else { //文件
					File file = new File(Cons.FILE_PATH_UPLOAD_CHUNKS + "/" + fileMd5);
					if (!file.exists()) {
						file.mkdir();
					}
					File chunkFile = new File(Cons.FILE_PATH_UPLOAD_CHUNKS + "/" + fileMd5 + "/" + chunk);
					FileUtils.copyInputStreamToFile(item.getInputStream(), chunkFile);
				}
			}

		} catch (FileUploadException | IOException e) {
			commonLogger.debug("文件上传失败！,Info: {}" ,e.getMessage());
		}
	}
}
